package cn.itcast.mobilebrowser.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import cn.itcast.mobilebrowser.dao.HistoryDao;
import cn.itcast.mobilebrowser.database.BrowserDatabase;
import cn.itcast.mobilebrowser.model.History;

public class HistoryViewModel extends AndroidViewModel {

    private final LiveData<List<History>> allHistory;

    private final HistoryDao historyDao;

    public HistoryViewModel(@NonNull @NotNull Application application) {
        super(application);
        historyDao = BrowserDatabase.getDataBase(application).getHistoryDao();
        allHistory = historyDao.getAllHistory();
    }

    public LiveData<List<History>> getAllHistory() {
        return allHistory;
    }

    public LiveData<List<History>> searchHistory(String webTitle) {
        return historyDao.getHistoryByTitle(webTitle);
    }

    public void insert(History history) {
        BrowserDatabase.databaseWriteExecutor.execute(() -> historyDao.insert(history));
    }

    public void delete(History history) {
        BrowserDatabase.databaseWriteExecutor.execute(() -> historyDao.deleteAll(history));
    }

    public void deleteAllHistory() {
        BrowserDatabase.databaseWriteExecutor.execute(historyDao::deleteAll);
    }

    public void update(History history) {
        BrowserDatabase.databaseWriteExecutor.execute(() -> historyDao.update(history));
    }
}
